package erChaShuFuXi;

public class erchashulianxi4 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
//左右根，左跟右，根左右
    class Solution {
        public int preIndex;
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            return buildTreeChild(preorder,inorder,0,inorder.length-1);
        }

        public TreeNode buildTreeChild(int[] preorder, int[] inorder,int inbegin,int inend) {
            //这种情况下 表明 当前root 没有子树了
            if(inbegin > inend) {
                return null;
            }
            TreeNode root = new TreeNode(preorder[preIndex]);
            int rootIndex = findVal(inorder,inbegin,inend,preorder[preIndex]);
            preIndex++;
            root.left = buildTreeChild(preorder,inorder,inbegin,rootIndex-1);
            root.right = buildTreeChild(preorder,inorder,rootIndex+1,inend);
            return root;
        }
        private int findVal(int[] inorder,int inbegin,int inend,int val) {
            for(int i = inbegin ;i <= inend;i++) {
                if(inorder[i] == val) {
                    return i;
                }
            }
            return -1;
        }

    }



    public int postIndex;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        postIndex = postorder.length-1;
        return buildTreeChild(inorder,postorder,0,postorder.length-1);
    }
    public TreeNode buildTreeChild(int[] inorder, int[] postorder,int inbegin,int inend) {
        //这种情况下 表明 当前root 没有子树了
        if(inbegin > inend) {
            return null;
        }
        TreeNode root = new TreeNode(postorder[postIndex]);

        int rootIndex = findVal(inorder,inbegin,inend,postorder[postIndex]);
        postIndex--;

        root.right = buildTreeChild(inorder,postorder,rootIndex+1,inend);
        root.left = buildTreeChild(inorder,postorder,inbegin,rootIndex-1);
        return root;
    }
    private int findVal(int[] inorder,int inbegin,int inend,int val) {
        for(int i = inbegin ;i <= inend;i++) {
            if(inorder[i] == val) {
                return i;
            }
        }
        return -1;
    }
}
